package ghostbanlistd;

import java.util.ArrayList;

public class Bans {
	ArrayList<Ban> bans;
	ArrayList<BanListener> listeners;
	
	public Bans() {
		bans = new ArrayList<Ban>();
		listeners = new ArrayList<BanListener>();
	}
	
	public void addBan(Ban ban) {
		synchronized(bans) {
			bans.add(ban);
		}
		
		for(BanListener listener : listeners) {
			listener.banAdded(ban);
		}
	}
	
	//todo: call this function every hour or so
	public void deleteOldBans() {
		//keep track of the bans that we remove so that we can call listeners outside of synchronized block
		ArrayList<Ban> removedBans = new ArrayList<Ban>();
		
		synchronized(bans) {
			for(int i = 0; i < bans.size(); i++) {
				//remove BOT_SPAM bans if they are older than 24 hours
				//remove any bans if they are older than a month
				if(bans.get(i).reasonCode == Ban.BAN_SPAM && bans.get(i).entryTime < System.currentTimeMillis() + 24 * 3600 * 1000) {
					removedBans.add(bans.remove(i));
					i--;
				} else if(bans.get(i).entryTime < System.currentTimeMillis() + 7 * 24 * 3600 * 1000) {
					removedBans.add(bans.remove(i));
					i--;
				}
			}
		}
		
		//now call listeners
		for(BanListener listener : listeners) {
			for(Ban ban : removedBans) {
				listener.banRemoved(ban);
			}
		}
	}
	
	//returns list of bans added after <time>
	public ArrayList<Ban> banList(long time) {
		ArrayList<Ban> list = new ArrayList<Ban>();
		
		synchronized(bans) {
			for(Ban ban : bans) {
				if(ban.entryTime > time) {
					list.add(ban);
				}
			}
		}
		
		return list;
	}
	
	public void addListener(BanListener listener) {
		listeners.add(listener);
	}
	
	public void removeListener(BanListener listener) {
		listeners.remove(listener);
	}
}
